# 107. 二叉树的层序遍历 II

// 给定一个二叉树,返回其节点值自底向上的层序遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
var levelOrderBottom = function(root) {
  const resArr = []

  let arr = [root]
  while (arr.length) {
    const res = []
    const length = arr.length
    for (let i = 0; i < length; i++) {
      const item = arr.shift()
      res.push(item.val)
      item.left && arr.push(item.left)
      item.right && arr.push(item.right)
    }
    resArr.unshift(res)
  }

  return resArr
}
console.log(
  levelOrderBottom({
    val: 3,
    left: {
      val: 9,
    },
    right: {
      val: 20,
      left: {
        val: 15,
      },
      right: {
        val: 7,
      },
    },
  })
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
Last Updated: 6/27/2023, 7:40:45 PM